package cn.simon.controller;

import cn.hutool.crypto.SecureUtil;
import cn.simon.model.BiliUser;
import cn.simon.service.Impl.LoginServiceImpl;
import cn.simon.util.Site;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet(value = "/login")
public class Bili_LoginController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher(Site.PREFIX + "/bilibili_login"+Site.SUFFIX).forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username  = req.getParameter("username");
        String password = req.getParameter("password");
        String verify = req.getParameter("verify");
        HttpSession session  = req.getSession();

        if(!session.getAttribute("code").equals(verify)){
            req.setAttribute("meg","验证码不正确");
            req.getRequestDispatcher(Site.PREFIX + "/bilibili_login" + Site.SUFFIX).forward(req,resp);
            return;
        }

        System.out.println(username + "------------"+password);

        LoginServiceImpl loginService = new LoginServiceImpl();
        BiliUser user = loginService.getPaword(username);
        password = SecureUtil.md5(password).toLowerCase();
        if(user != null){
            if(user.getBiliuserPassword().equals(password)){
                session.setAttribute("username",username);
                resp.sendRedirect(req.getContextPath()+"/head");
                return;
            }
        }
        req.setAttribute("meg","账号或密码错误");
        req.getRequestDispatcher(Site.PREFIX + "/bilibili_login" + Site.SUFFIX).forward(req,resp);

    }
}
